package com.fjrcloud.service;

import com.fjrcloud.dao.IdentifiedHomesteadDao;
import com.fjrcloud.dao.IdentifiedStorefrontDao;
import com.fjrcloud.entity.HouseholdMaster;
import com.fjrcloud.entity.IdentifiedHomestead;
import com.fjrcloud.entity.IdentifiedStorefront;
import com.fjrcloud.entity.StorefrontStandard;
import com.fjrcloud.exception.BusinessException;
import com.fjrcloud.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

/**
 * Created by shengjian.lin on 2017/1/22.
 */
@Service
public class IdentifiedHomesteadService {

    @Autowired
    private IdentifiedHomesteadDao identifiedHomesteadDao;
    @Autowired
    private StorefrontStandardService standardService;
    @Autowired
    private HouseholdService householdService;

    public IdentifiedHomestead save(Integer id, Integer masterId, Double area, String description) throws BusinessException {

        HouseholdMaster master = findMaster(masterId);

        if (area == null)
            throw new BusinessException("面积错误");

        IdentifiedHomestead identified;
        if (id == null)
            identified = new IdentifiedHomestead();
        else
            identified = identifiedHomesteadDao.findOne(id);

        if (identified == null)
            throw new BusinessException("无效的保存对象");

        identified.setMaster(master);
        identified.setArea(area);
        identified.setDescription(description);
        identified.setCreateTime(System.currentTimeMillis());

        return identifiedHomesteadDao.save(identified);
    }

    private HouseholdMaster findMaster(Integer masterId) throws BusinessException {
        if (masterId == null)
            throw new BusinessException("无效认证主体信息");
        HouseholdMaster master = householdService.getMaster(masterId);
        if (master == null)
            throw new BusinessException("无效认证主体信息");

        return master;
    }
    private PageRequest findPage(Integer pageNum, Integer pageSize) {
        pageNum = PageUtils.checkPageNum(pageNum);
        pageSize = PageUtils.checkPageSize(pageSize);
        PageRequest pageRequest = new PageRequest(pageNum, pageSize);

        return pageRequest;
    }
    public Page<IdentifiedHomestead> find(Integer masterId, Integer pageNum, Integer pageSize) throws BusinessException {

        return identifiedHomesteadDao.findByValidAndMasterOrderByCreateTimeAsc(true,findMaster(masterId),findPage(pageNum,pageSize));

    }
    public IdentifiedHomestead get(Integer id){
        return identifiedHomesteadDao.findOne(id);
    }

    public void del(Integer id){
        identifiedHomesteadDao.delete(id);
    }
}
